import React, { Component, Fragment } from 'react';
import { Divider, Dropdown, Menu, Icon } from 'antd';
import PropTypes from 'prop-types';

export default class OperateButtons extends Component {
  static defaultProps = {
    buttons: [],
    dropdownText: '更多',
    trigger: ['click'],
  };

  static propTypes = {
    buttons: PropTypes.array,
    dropdownText: PropTypes.string,
    trigger: PropTypes.array,
  };

  events = {};

  constructor(props) {
    super(props);
    props.buttons.map(b => {
      this.events[b.key] = b.onClick;
      return b;
    });
  }

  menuClick = e => {
    const { key, domEvent } = e;

    if (typeof this.events[key] === 'function') {
      return this.events[key](domEvent);
    }
    return undefined;
  };

  aClick = (key, domEvent) => {
    if (typeof this.events[key] === 'function') {
      return this.events[key](domEvent);
    }
    return undefined;
  };

  render() {
    const { buttons, max, dropdownText, trigger } = this.props;
    const children = [];
    // 长度超过max时，显示更多
    if (max && buttons.length > max) {
      const items = buttons.slice(max - 1);
      const menu = (
        <Menu onClick={this.menuClick}>
          {items.map(item => (
            <Menu.Item key={item.key}>{item.name}</Menu.Item>
          ))}
        </Menu>
      );
      const LastItem = (
        <Dropdown key="dropdown" overlay={menu} trigger={trigger}>
          <a className="ant-dropdown-link">
            {dropdownText} <Icon type="down" />
          </a>
        </Dropdown>
      );
      buttons.slice(0, max - 1).map(button => {
        children.push(
          <a
            key={`b_${button.key}`}
            {...button}
            onClick={e => {
              this.aClick(button.key, e);
            }}
          >
            {button.name}
          </a>,
        );
        children.push(<Divider key={`d_${button.key}`} type="vertical" />);
        return children;
      });
      children.push(LastItem);
    } else {
      buttons.map(button => {
        children.push(
          <a key={`b_${button.key}`} {...button}>
            {button.name}
          </a>,
        );
        children.push(<Divider key={`d_${button.key}`} type="vertical" />);
        return children;
      });
      children.pop();
    }

    return <Fragment>{children}</Fragment>;
  }
}
